#include "Setting.h"
//Setting setting;  // 定义 'setting' 对象
Setting &Setting::getInstance() {
  static Setting instance;
  return instance;
}
Setting::Setting() {
  manager = localStorage.getItem("manager");  //获取本地管理用户名密码json文本
  if (manager == "") { //若不存在则配置默认值
    setAdmin("admin","admin99999");                                
  }
  manager = localStorage.getItem("manager");  //获取本地管理用户名密码json文本
  managerObj = JSON.parse(manager);           //获取JSON对象
}
/* 匹配管理员名称及密码是否正确*/
bool Setting::adminMatching(const String &username, const String &password) {
 /*  username.trim();
  password.trim(); */
  if(JSON.typeof(managerObj)!="object")return false;
  
  
  return (String)managerObj["username"] == username && (String)managerObj["password"] == password;
}
/*设置管理员名称及密码 */
bool Setting::setAdmin(String username,String password) {
 password.trim();
 username.trim();
  if (password != "" && username != "") {
    String jsonkey = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}" + String(random(100000, 1000000));  //密钥原始字符串
    String jsonManager = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"adminkey\":\"" + md5_string((char *)jsonkey.c_str()) + "\"}";
    managerObj = JSON.parse(jsonManager);
    localStorage.setItem("manager", jsonManager);
    return true;
  } else {
    return false;
  }
}


/* 获取管理员用户名密码匹配的adminKey值 */
String Setting::getAdminKey(const String &username,const String &password){
  if(adminMatching(username,password)==true){
    return "{\"adminkey\":\"" + (String)managerObj["adminkey"] + "\"}";
  }else{
    return "{\"err\":\"管理员或密码错误!\"}";
  }
 //return adminMatching(username, password)==true?"{\"adminkey\":\"" + (String)managerObj["adminkey"] + "\"}":"{\"err\":\"管理员或密码错误!\"}";
}


/* 修改管理员名称及密码 */
String Setting::changeAdmin(const String &username, const String &oldpassword, const String &newpassword) {
  if (adminMatching(username, oldpassword) && setAdmin(username,newpassword)) {
    return "{\"adminkey\":\"" + (String)managerObj["adminkey"] + "\"}";
  } else {
    return "{\"err\":\"管理员或密码错误!修改失败!\"}";
  }
}

/* 根据判断管理员用户名密码正确返回用户列表包括密码 */
String Setting::getUserList(const String &username, const String &password) {
  return adminMatching(username,password)==true ? localStorage.getItem("key") : "{\"err\":\"管理员或密码错误!\"}";
}
/* 根据判断管理员用户名密码adminkey值返回正确返回用户列表包括密码 */
String Setting::getUserList(const String &adminkey) {
  return (String)managerObj["adminkey"] == adminkey ? localStorage.getItem("key") : "{\"err\":\"管理员或密码错误!\"}";
}

/*设置用户列表测试可否进行整体JSON保存------------------------------------------------*/
bool Setting::setUserList(const String &adminkey,const String &userList) {
  /* String sub = str.substring(0, 14);
  if (sub == "[{\"username\":\"") {
  } */
}